import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { Auths } from '@/utils/types.d';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { message, Modal } from 'antd';
import { useState } from 'react';
import { useModel } from 'umi';
import { updateRefund } from '../../service';
import { PaymentRecordItem, PaymentRefundStatus, PayStatus, RefundRecordItem } from '../../types.d';
import { PaymentStatus } from '../../types.d';
import { PayMode } from '../../types.d';
import RefundModal from './RefundModal';

// 获取当前订单在该笔支付记录中所占金额
const getCurrOrderPayAmount = (orderNo: string, record?: PaymentRecordItem) => {
  if (!record) return 0;
  if (record.orderNos?.length > 0) {
    return record.orderInfos?.find((item) => item?.orderNo == orderNo)?.amount || 0;
  } else if (record.orderNo) {
    return record.amount || 0;
  }
  return 0;
};

export default (props: {
  records?: PaymentRecordItem[];
  refresh: () => void;
  carOut?: boolean;
  orderNo: string;
  canRefundAmount: number;
  refundRecords: RefundRecordItem[];
  payStatus: PayStatus;
}) => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.parkingOrder || []) : new Set();
  const ifModify = auths.has(Auths.MODIFY);
  const {
    records = [],
    carOut = false,
    canRefundAmount = 0,
    orderNo,
    refundRecords = [],
    payStatus,
  } = props;
  const [chillDowning, setChillDowning] = useState<number>(0);
  if (chillDowning > -1) {
    setTimeout(() => {
      setChillDowning(chillDowning - 1);
    }, 1000);
  }
  const columns: ProColumns<PaymentRecordItem>[] = [
    {
      title: 'id',
      hideInTable: true,
      hideInSearch: true,
      hideInForm: true,
      dataIndex: '_id',
    },
    {
      title: '支付记录编号',
      align: 'center',
      dataIndex: 'payOrderNo',
    },
    {
      title: '支付方式',
      align: 'center',
      dataIndex: 'payMode',
      valueEnum: {
        [PayMode.TENPAY]: { text: '微信支付' },
        [PayMode.ALIPAY]: { text: '支付宝' },
        [PayMode.CASH]: { text: '现金支付' },
        [PayMode.THIRD_PARTY]: { text: '第三方平台' },
        [PayMode.ETC]: { text: 'ETC助缴' },
        [PayMode.UNKNOWN]: { text: '其他' },
      },
    },
    {
      title: '支付金额',
      valueType: 'money',
      align: 'center',
      dataIndex: 'amount',
      renderText: (text) => (text / 100).toFixed(2),
    },
    {
      title: '支付状态',
      align: 'center',
      dataIndex: 'paymentStatus',
      valueEnum: {
        [PaymentStatus.ONGOING]: { text: '正在支付' },
        [PaymentStatus.SUCCESS]: { text: '成功' },
        [PaymentStatus.NOTPAY]: { text: '未支付' },
        [PaymentStatus.CLOSED]: { text: '已关闭' },
        [PaymentStatus.REVOKED]: { text: '已撤销' },
        [PaymentStatus.USERPAYING]: { text: '用户支付中' },
        [PaymentStatus.PAYERROR]: { text: '支付失败' },
      },
    },
    {
      title: '发起时间',
      align: 'center',
      dataIndex: 'createTime',
      valueType: 'dateTime',
    },
    {
      title: '支付时间',
      align: 'center',
      dataIndex: 'payTime',
      valueType: 'dateTime',
    },
    {
      title: '收费员',
      align: 'center',
      dataIndex: 'cashier',
      renderText: (val) => val || '暂无数据',
    },
    {
      title: '已退款金额',
      align: 'center',
      dataIndex: 'payOrderNo',
      hideInSearch: true,
      valueType: 'money',
      renderText: (_, record) => {
        // 过滤出当前订单当前支付记录中的已退款部分
        const currPayRefunds = refundRecords?.filter((item) => item.payNo == record.payNo);
        const tempRefunded = currPayRefunds?.reduce((prev, next) => prev + next.amount, 0) || 0;
        return (tempRefunded / 100).toFixed(2);
      },
    },
    {
      title: '退款状态',
      align: 'center',
      dataIndex: 'isRefund',
      valueEnum: {
        0: { text: '未退款' },
        1: { text: '退款中' },
        2: { text: '已退款' },
        3: { text: '部分退款' },
      },
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      hideInTable: !carOut,
      render: (_, record) => {
        if (!ifModify) return [<PlaceHolderCpn key={`${record._id}_noauth`} text={'无权限操作'} />];
        if (
          record.payMode == PayMode.THIRD_PARTY ||
          //  ||
          // record.payMode == PayMode.ETC ||
          payStatus == PayStatus.PARI_PAID
        )
          return [<PlaceHolderCpn key={`${record._id}_noauth`} text={'不支持退款'} />];
        if (chillDowning > 0) {
          return [
            <PlaceHolderCpn key={`${record._id}_noauth`} text={`操作冷却中${chillDowning}s`} />,
          ];
        }
        if (record.isRefund == PaymentRefundStatus.REFUNDED) {
          return [<PlaceHolderCpn key={`${record._id}_noauth`} text={'已退款'} />];
        }
        if (record.isRefund == PaymentRefundStatus.WAIT_REFUND && record.payMode != PayMode.ETC) {
          return [<PlaceHolderCpn key={`${record._id}_noauth`} text={'退款中'} />];
        }
        if (record.payMode == PayMode.ETC) {
          return [
            record.isRefund == PaymentRefundStatus.WAIT_REFUND ? (
              <a
                onClick={() => {
                  Modal.confirm({
                    title: '更新ETC退款进度',
                    content: '是否更新ETC退款进度',
                    onOk: async () => {
                      message.loading({
                        content: '正在查询...',
                        key: 'update_etc_refund',
                      });
                      const res = await updateRefund(record.payNo);
                      if (!res.success) {
                        message.error({
                          content: res.message,
                          key: 'update_etc_refund',
                        });
                        return false;
                      }
                      message.success({
                        content: '更新成功',
                        key: 'update_etc_refund',
                      });
                      props.refresh();
                      return true;
                    },
                  });
                }}
              >
                更新
              </a>
            ) : (
              <RefundModal
                key={`${record._id}_refund`}
                payOrderNo={record.payOrderNo}
                reload={() => {
                  props.refresh();
                  setChillDowning(7);
                }}
                orderNo={orderNo}
                maxAmount={record.amount}
                minAmount={record.amount}
              />
            ),
          ];
        }
        const currOrderPayInfo = getCurrOrderPayAmount(orderNo, record);
        // // 过滤出当前订单当前支付记录中的已退款部分
        // const currPayRefunds = refundRecords?.filter((item) => item.payNo == record.payNo);
        // const tempRefunded = currPayRefunds?.reduce((prev, next) => prev + next.amount, 0) || 0;
        const currPayRefunds = refundRecords?.filter((item) => item.payNo == record.payNo);
        const tempRefunded = currPayRefunds?.reduce((prev, next) => prev + next.amount, 0) || 0;
        const diff = currOrderPayInfo - tempRefunded;
        if (diff <= 0)
          return [<PlaceHolderCpn key={`${record._id}_noauth`} text={'无可退款金额'} />];

        return [
          <RefundModal
            key={`${record._id}_refund`}
            payOrderNo={record.payOrderNo}
            reload={() => {
              props.refresh();
              setChillDowning(7);
            }}
            orderNo={orderNo}
            maxAmount={Math.min(diff, canRefundAmount)}
          />,
        ];
        // if(record)
        //   ifModify &&
        //   record?.isRefund == PaymentRefundStatus.NORMAL &&
        //   record?.orderInfos?.length > 0 ? (
        //     <RefundModal
        //       payOrderNo={record.payOrderNo}
        //       reload={() => {
        //         props.refresh();
        //       }}
        //     />
        //   ) : (
        //     <PlaceHolderCpn text={ifModify ? '无需操作' : '无权限操作'} />
        //   )
      },
    },
  ];
  return (
    <ProTable
      columns={columns}
      rowKey="_id"
      scroll={{ x: true }}
      style={{ whiteSpace: 'nowrap' }}
      dataSource={records}
      // pagination={false}
      pagination={{
        showSizeChanger: true,
        defaultPageSize: 5,
        pageSizeOptions: [5, 10],
      }}
      toolBarRender={false}
      search={false}
    />
  );
};
